package com.feng.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.usercenter.common.BaseResult;
import com.feng.usercenter.common.ErrorCode;
import com.feng.usercenter.constant.BaseConst;
import com.feng.usercenter.exception.BusinessException;
import com.feng.usercenter.service.UserService;
import com.feng.usercenter.model.User;
import com.feng.usercenter.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
* @author 34689
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-06-18 20:58:34
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    /**
     * 用于加密
     */
    private static final String SALT = "liquor";


    @Resource
    private UserMapper userMapper;
    /**
     * @param userAccount   账户
     * @param userPassword  密码
     * @return 用户信息（脱敏）
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "账户或密码为空！");
        }
        if (userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户或密码格式不符合要求！");
        }

        // 不能包含特殊字符
        String validPattern = "[\\p{Punct}\\p{S}\\s]"; // 标点、符号、空白
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);

        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符！");
        }

        // 2. 密码加密转换
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("用户登录失败");
            throw new BusinessException(ErrorCode.NULL_ERROR, "不存在该用户！");
        }

        // 3. 用户信息脱敏
        User safeUser = getSafetyUser(user);

        // 4. 记录用户登录态
        request.getSession().setAttribute(BaseConst.USER_LOGIN_STATUS, safeUser);
        return safeUser;
    }

    /**
     * @param userAccount   账户
     * @param userPassword  密码
     * @param checkPassword 校验码
     * @param planetCode 星球编号
     * @return 注册
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {

        // 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "参数为空！");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短！");
        }
        if (userPassword.length() < 8 ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短！");
        }
        if (!checkPassword.equals(userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致！");
        }
        if (planetCode.length() > 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长！");
        }

        // 用户账号不能包含特殊字符
        String validPattern = "[\\p{Punct}\\p{S}\\s]"; // 标点、符号、空白
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);

        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号包括非法字符！");
        }


        // 账号不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该账户已存在！");
        }

        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该星球编号已存在！");
        }

        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean flag = this.save(user);
        if (!flag) {
            throw new RuntimeException("系统错误！");
        }

        return user.getId();
    }

    /**
     * @param username 用户昵称
     * @return 用户列表
     */
    @Override
    public List<User> searchUsers(String username) {

        if (StringUtils.isNotBlank(username)) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("username", username);
            return userMapper.selectList(queryWrapper);
        }
        throw new BusinessException(ErrorCode.NULL_ERROR, "请求参数为空！");
    }

    /**
     * 用户脱敏
     * @param originalUser 原始用户
     * @return 脱敏用户
     */
    @Override
    public User getSafetyUser(User originalUser) {
        if (originalUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR, "用户参数为空！");
        }
        User safeUser = new User();
        safeUser.setId(originalUser.getId());
        safeUser.setUsername(originalUser.getUsername());
        safeUser.setUserAccount(originalUser.getUserAccount());
        safeUser.setAvatarUrl(originalUser.getAvatarUrl());
        safeUser.setGender(originalUser.getGender());
        safeUser.setPhone(originalUser.getPhone());
        safeUser.setEmail(originalUser.getEmail());
        safeUser.setUserStatus(originalUser.getUserStatus());
        safeUser.setCreateTime(originalUser.getCreateTime());
        safeUser.setUserRole(originalUser.getUserRole() );
        safeUser.setPlanetCode(originalUser.getPlanetCode());
        return safeUser;

    }

    /**
     * 用户注销
     * @param request 请求
     * @return 默认
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(BaseConst.USER_LOGIN_STATUS);
        return 1;
    }
}




